"""
用户账户相关功能:注册、短信、登录、注销
"""
from django.shortcuts import render, HttpResponse
from django.http import JsonResponse
from utils import helper
from utils.tencent.sms import send_sms_single
from django.conf import settings
from django_redis import get_redis_connection
from web import models
import random


# 注册功能
def reg(request):
    if request.method == 'GET':
        return render(request, 'reg.html')
    else:
        username = request.POST.get('username')
        email = request.POST.get('email')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        moblie_phone = request.POST.get('moblie_phone')
        code = request.POST.get('code')

        # 判断用户名是否存在
        if username == "":
            return JsonResponse({'status': False, 'error': {'username': ['您还没有填写', ]}})
        exists = models.Userinfo.objects.filter(username=username).exists()
        if exists:
            return JsonResponse({'status': False, 'error': {'username': ['用户名已存在', ]}})

        # 判断邮箱是否存在
        exists2 = models.Userinfo.objects.filter(email=email).exists()
        if exists2:
            return JsonResponse({'status': False, 'error': {'email': ['邮箱已存在', ]}})

        # 判断邮箱格式是否正确
        if not helper.judge_email(email):
            return JsonResponse({'status': False, 'error': {'email': ['邮箱格式错误', ]}})

        # 判断两次输入的密码是否一样
        if password != password2:
            return JsonResponse({'status': False, 'error': {'password2': ['两次输入的密码不一样', ]}})

        # 判断密码长度大于6位小于16位
        if 16 < len(password):
            return JsonResponse({'status': False, 'error': {'password': ['密码长度不能小于6位，且不能不能大于16位', ]}})
        elif 6 > len(password):
            return JsonResponse({'status': False, 'error': {'password': ['密码长度不能小于6位，且不能不能大于16位', ]}})

        # 重新验证手机号
        exists = models.Userinfo.objects.filter(moblie_phone=moblie_phone).exists()
        if exists:
            return JsonResponse({'status': False, 'error': {'moblie_phone': ['手机号已存在', ]}})

        # 验证验证码是否正确
        conn = get_redis_connection()
        redis_code = conn.get(moblie_phone)
        if not redis_code:
            return JsonResponse({'status': False, 'error': {'code': ['验证码失效或未发送', ]}})
        redis_str_code = redis_code.decode('utf-8')
        if code.strip() != redis_str_code:
            return JsonResponse({'status': False, 'error': {'code': ['验证码错误，请重新输入', ]}})

        # 验证通过写入数据库
        create = models.Userinfo.objects.create(username=username,
                                                email=email,
                                                password=helper.password_encrypt(password),
                                                moblie_phone=moblie_phone)
        if create.id > 0:
            return JsonResponse({'status': True})
        else:
            return JsonResponse({'status': False, 'error': {'sum': ['注册失败请重试']}})


# 发注册短信功能
def send_sms(request):
    if request.method == 'POST':
        tpl = request.POST.get('tpl')
        moblie_phone = request.POST.get('moblie_phone')

        # 只是验证手机号：不能为空、格式是否正确
        if not helper.judge_phone(moblie_phone):
            return JsonResponse({'status': False, 'error': '手机号格式错误'})

        # 判断短信模板是否存在
        template_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)
        if not template_id:
            return JsonResponse({'status': False, 'error': '短信模板错误'})

        # 检验数据库中是否存在该手机号
        exists = models.Userinfo.objects.filter(moblie_phone=moblie_phone).exists()
        if exists:
            return JsonResponse({'status': False, 'error': '手机号已存在'})

        # 发短信
        code = random.randrange(100000, 999999)
        sms = send_sms_single(moblie_phone, template_id, [code, ])
        if sms['result'] != 0:
            return JsonResponse({'status': False, 'error': "短信发送失败，{}".format(sms['errmsg'])})

        # 将验证码写入redis
        conn = get_redis_connection()
        conn.set(moblie_phone, code, ex=60)
        return JsonResponse({'status': True})
    else:
        return HttpResponse('错误的访问方式！')
